package cn.otrue.patienthealthmanager.activity;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.bean.ChatModle;
import cn.otrue.patienthealthmanager.utils.MyConst;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;

/**
 * 引导页 目前完成本地图片显示没有
 * 
 * @author G
 * 
 */
public class GuideActivity extends BaseActivity {

	/** Viewpager对象 */
	private ViewPager viewPager;
	private ImageView imageView;
	/** 创建一个数组，用来存放每个页面要显示的View */
	private ArrayList<View> pageViews;
	/** 创建一个imageview类型的数组，用来表示导航小圆点 */
	private ImageView[] imageViews;
	/** 装显示图片的viewgroup */
	private ViewGroup viewPictures;
	/** 导航小圆点的viewgroup */
	private ViewGroup viewPoints;

	private Bitmap bitmap = null;
	private BitmapDrawable bd = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		SharedPreferences share = getSharedPreferences("guid",
				Context.MODE_PRIVATE);
		String trueOrNo = share.getString("true", "");
		if ("".equals(trueOrNo)) {
			Editor edit = share.edit();
			edit.putString("true", "true");
			edit.commit();
			try {
				initDb();
			} catch (DbException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("true".equals(trueOrNo)) {
			Intent intent = new Intent(GuideActivity.this, MainActivity.class);
			startActivity(intent);
			GuideActivity.this.finish();
		}
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		LayoutInflater inflater = getLayoutInflater();

		initViewPagers(inflater);
		// 小圆点数组，大小是图片的个数
		imageViews = new ImageView[pageViews.size()];
		// 从指定的XML文件中加载视图
		viewPictures = (ViewGroup) inflater.inflate(R.layout.activity_guide,
				null);

		viewPager = (ViewPager) viewPictures
				.findViewById(R.id.vp_guide_viewpager);
		viewPager.setOffscreenPageLimit(0);
		viewPoints = (ViewGroup) viewPictures
				.findViewById(R.id.ll_gide_viewpoints);

		// 添加小圆点导航的图片
		for (int i = 0; i < pageViews.size(); i++) {
			imageView = new ImageView(GuideActivity.this);
			imageView.setLayoutParams(new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			imageView.setPadding(5, 0, 5, 0);
			// 吧小圆点放进数组中
			imageViews[i] = imageView;
			// 默认选中的是第一张图片，此时第一个小圆点是选中状态，其他不是
			if (i == 0)
				imageViews[i].setImageDrawable(getResources().getDrawable(
						R.drawable.page_indicator_focused));
			else
				imageViews[i].setImageDrawable(getResources().getDrawable(
						R.drawable.page_indicator_unfocused));
			// 将imageviews添加到小圆点视图组
			viewPoints.addView(imageViews[i]);
		}

		setContentView(viewPictures);

		viewPager.setAdapter(new NavigationPageAdapter());
		// 为viewpager添加监听，当view发生变化时的响应
		viewPager.setOnPageChangeListener(new NavigationPageChangeListener());
	}

	private void initDb() throws DbException {
		DbUtils db = DbUtils.create(this);
		ChatModle chat = new ChatModle("", "", "", "", "test", "",
				MyConst.CHAT_OUT, new Date(), 0);

		db.save(chat);

	}

	private void initViewPagers(LayoutInflater inflater) {
		int layoutId1;
		int layoutId2;
		int layoutId3;

		layoutId1 = R.drawable.guide1;
		layoutId2 = R.drawable.guide2;
		layoutId3 = R.drawable.guide3;

		pageViews = new ArrayList<View>();
		View view = inflater.inflate(R.layout.fragment_guide_item, null);
		RelativeLayout ll1 = (RelativeLayout) view
				.findViewById(R.id.ll_catt_viewpager);
		bitmap = readBitMap(layoutId1);
		bd = new BitmapDrawable(bitmap);
		ll1.setBackgroundDrawable(bd);
		pageViews.add(view);
		View view2 = inflater.inflate(R.layout.fragment_guide_item, null);
		RelativeLayout ll2 = (RelativeLayout) view2
				.findViewById(R.id.ll_catt_viewpager);
		bitmap = readBitMap(layoutId2);
		bd = new BitmapDrawable(bitmap);
		ll2.setBackgroundDrawable(bd);
		pageViews.add(view2);
		View view3 = inflater.inflate(R.layout.fragment_guide_item, null);
		RelativeLayout ll5 = (RelativeLayout) view3
				.findViewById(R.id.ll_catt_viewpager);
		bitmap = readBitMap(layoutId3);
		bd = new BitmapDrawable(bitmap);
		ll5.setBackgroundDrawable(bd);
		view3.findViewById(R.id.tv_catt_startbutton)
				.setVisibility(View.VISIBLE);
		view3.findViewById(R.id.tv_catt_startbutton).setOnClickListener(this);
		pageViews.add(view3);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bitmap != null) {
			if (!bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}
		System.gc();
	}

	/**
	 * 以最省内存的方式读取本地资源的图片
	 * 
	 * @param resId
	 * @return
	 */
	public Bitmap readBitMap(int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = this.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	// 导航图片view的适配器，必须要实现的是下面四个方法
	class NavigationPageAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return pageViews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		// 初始化每个Item
		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager) container).addView(pageViews.get(position));
			return pageViews.get(position);
		}

		// 销毁每个Item
		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView(pageViews.get(position));
		}

	}

	// viewpager的监听器，主要是onPageSelected要实现
	class NavigationPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int position) {
			// 循环主要是控制导航中每个小圆点的状态
			for (int i = 0; i < imageViews.length; i++) {
				// 当前view下设置小圆点为选中状态
				imageViews[i].setImageDrawable(getResources().getDrawable(
						R.drawable.page_indicator_focused));
				// 其余设置为飞选中状态
				if (position != i)
					imageViews[i].setImageDrawable(getResources().getDrawable(
							R.drawable.page_indicator_unfocused));
			}
		}

	}

	// 开始按钮方法，开始按钮在XML文件中onClick属性设置；
	// 我试图把按钮在本activity中实例化并设置点击监听，但总是报错，使用这个方法后没有报错，原因没找到
	public void startbutton(View v) {
		Intent intent = new Intent(GuideActivity.this, MainActivity.class);
		startActivity(intent);
		GuideActivity.this.finish();
	}

	@Override
	public void onClick(View view) {
		startbutton(view);
	}

}
